<?php

namespace App\Http\Controllers\Answer;

use App\App\Services\Web\UserService;
use App\Contracts\Repositories\ActivityRepository as ActivityRepositoryContact;
use App\Events\ActivityCommonCreated;
use App\Events\ActivityCommonUpdated;
use App\Entities\Activity;
use App\Entities\ActivityModel;
use App\Entities\AnswerHonor;
use App\Entities\AnswerList;
use App\Http\Controllers\Activity\BaseController;
use App\Morefun\Publishing\Publisher;
use Carbon\Carbon;
use Illuminate\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class ActivityController extends BaseController
{
    protected $redis;

    public function __construct(UserService $user, ActivityRepositoryContact $activities)
    {
        parent::__construct($user, $activities);
    }

    protected function redis(){
        if(!$this->redis){
            $this->redis = Container::getInstance()->make('redis');
        }
        return $this->redis;
    }

    public function show($id)
    {
        $activity = $this->activities->findOne($id);

        if (null === $activity) {
            return response()->failed('没有找到资源');
        }

        //$storage = Container::getInstance()->make(StorageServiceContract::class);

        $translated = [
            'id'               => $activity->id,
            'category'         => $activity->category,
            'name'             => $activity->name,
            'start_time'       => $activity->startTime,
            'end_time'         => $activity->endTime,
            'limit'            => \GuzzleHttp\json_decode($activity->limit),
            //'background_img'   => $storage->toHttpUrl($activity->backgroundImg),
            'description'      => $activity->description,
            'app_url'          => $activity->app_url,
            'publishing'       => \GuzzleHttp\json_decode($activity->publishing_ways, true),
            'shares'           => $this->formatShares($activity->shares),
        ];

        $answerHonor = AnswerHonor::query()->where('activity','=',$activity->id)->get()->toArray();
        $answerList   = AnswerList::query()->where('activity','=',$activity->id)->get()->toArray();

        return response()->success([
            'activity' => $translated,
            'honor'   => $answerHonor,
            'list'       => $answerList
        ]);
    }

    public function update(Request $request, $id)
    {
        $activity = Activity::query()->where('id', $id)->first();
        if (null === $activity) {
            return response()->failed('没有找到这个活动');
        }
        $input = $request->json()->all();
        $validator = Validator::make($input, $this->getRulesForUpdate());
        if ($validator->fails()) {
            return response()->failed(Arr::first($validator->errors()->all()));
        }

        $input = $this->translateInputFromRequest($request);
        // 去掉不可修改的值
        Arr::forget($input, ['user_id', 'group_code', 'model_id', 'template_id']);
        $activity->fill($input);

        $database = Container::getInstance()->make('db');

        $success = $database->transaction(function () use ($activity,$input) {
            $activity->save();
            AnswerList::query()->insert(parseLimits($input['answer_list']));
            AnswerHonor::query()->insert(parseLimits($input['honor_list']));
            $info = ActivityInfo::query()->find($activity->getAttribute('id'));
            if (!$info) {
                return true;
            }

            $info->setAttribute('name', $activity->getAttribute('name'));
            return $info->save();
        });

        if ($success) {
            $this->redis()->setex(
                'answer:'.$id,
                strtotime($input['end_time'])-time(),
                json_encode(
                    $this->parseLimits($input['answer_list'],2)
                )
            );
            $this->redis()->setex('honor:'.$id,
                strtotime($input['end_time'])-time(),
                json_encode(
                    $this->parseLimits($input['honor_list'])
                )
            );
            $this->updatedEvents($activity);
            return response()->success();
        }

        return response()->failed('活动修改失败');
    }

    public function notRelated(Request $request)
    {
        $without = $request->get('without');
        $type = $request->get('type');

        $query = Activity::query();
        $now = Carbon::now()->toDateTimeString();

        $query->where('endTime', '<', $now);

        if ($type) {
            $modelId = ActivityModel::query()->where('rule', $type)->value('id');
            if ($modelId) {
                $query->where('model_id', $modelId);
            }
        }

        if ($without) {
            $query->where('id', '!=', $without);
        }

        return response()->success($query->get(['id', 'name']));
    }

    protected function getRulesForCreate()
    {
        return [
            'name'                 => 'required|max:255',
            'category'             => 'required|in:1,2',
            'start_time'           => 'required|date',
            'end_time'             => 'required|date|after:start_time',
            'model_id'             => 'required',
            'template_id'          => 'required',
            'description'          => 'min:1',
            //'validations'          => 'array',
            //'validations.type'     => 'in:IP,MOBILE,VERIFY_CODE,PASSWORD',
            //'validations.password' => 'required_if:validations.type,PASSWORD',
            'shares'               => 'array',
            'shares.title'         => 'required_if:shares.isopen,on',
            'shares.content'       => 'required_if:shares.isopen,on',
        ];
    }

    protected function getRulesForUpdate()
    {
        return [
            'name'                 => 'max:255',
            'category'             => 'in:1,2',
            'start_time'           => 'date',
            'end_time'             => 'date|after:startTime',
            'description'          => 'min:1',
            'answer_backgroud'=>'required',
            'is_display'            =>'in:0,1',
            'answer_count'      =>'Numeric',
            'is_random'           =>'in:0,1',
            'answer_list'          =>'array',
            'honor_list'          =>'array',

            //'validations'          => 'array',
            //'validations.type'     => 'in:IP,MOBILE,VERIFY_CODE,PASSWORD',
            //'validations.password' => 'required_if:validations.type,PASSWORD',
            //'relation'             => 'array',
            //'relation.id'          => 'uuid',
        ];
    }

    protected function parseRules(Request $request)
    {
        return json_encode([
            'validations' => $request->json('validations', []),
            // 关联其他活动
            'relation'    => ['id' => $request->get('relation.id', '')],
        ]);
    }

    protected function parseLimits(Request $request,$type=1)
    {
        foreach ($request as &$v){
            $v = json_decode($v);
        }
        if($type = 2){
            foreach ($request as &$av){
                unset($av['right']);
            }
        }
        return $request;
    }

    protected function createdEvents(Activity $activity)
    {
        return event(new ActivityCommonCreated($activity));
    }

    protected function updatedEvents(Activity $activity)
    {
        return event(new ActivityCommonUpdated($activity));
    }
}
